package com.ruoyi.service.service.impl;

import com.ruoyi.service.domain.ServiceLog;
import com.ruoyi.service.domain.ServiceOrders;
import com.ruoyi.service.domain.ServiceReason;
import com.ruoyi.service.domain.ServiceUsers;
import com.ruoyi.service.entity.user.PCUserDetailRet;
import com.ruoyi.service.entity.user.PCUserListRet;
import com.ruoyi.service.entity.user.PCUserLog;
import com.ruoyi.service.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

@Component
public class PcUserService {


    @Autowired
    private ServiceOrdersMapper ordersMapper;

    @Autowired
    private ServiceNurseMapper nurseMapper;

    @Autowired
    private ServiceMycartMapper mycartMapper;

    @Autowired
    private ServiceItemscomboMapper itemscomboMapper;

    @Autowired
    private ServiceComboMapper comboMapper;

    @Autowired
    private ServiceItemsMapper itemsMapper;

    @Autowired
    private ServiceAddressMapper addressMapper;

    @Autowired
    private ServicePayroadMapper payroadMapper;

    @Autowired
    private ServiceOrderscomboMapper orderscomboMapper;

    @Autowired
    private ServiceOrdersitemsMapper ordersitemsMapper;

    @Autowired
    private ServicePackagescomboMapper packagescomboMapper;

    @Autowired
    private ServicePackagesMapper packagesMapper;

    @Autowired
    private ServiceOrderspackagesMapper orderspackagesMapper;

    @Autowired
    private ServicePayMapper payMapper;

    @Autowired
    private ServiceAssessmentMapper assessmentMapper;

    @Autowired
    private ServicePictureMapper pictureMapper;

    @Autowired
    private ServiceCodeMapper codeMapper;

    @Autowired
    private ServiceRefuseMapper refuseMapper;

    @Autowired
    private ServiceOrdernurseMapper ordernurseMapper;

    @Autowired
    private ServiceServedMapper servedMapper;

    @Autowired
    private ServiceUsersMapper usersMapper;

    @Autowired
    private ServiceReasonrefuseMapper reasonrefuseMapper;

    @Autowired
    private ServiceOrderotherpayMapper orderotherpayMapper;

    @Autowired
    private ServiceTimeMapper timeMapper;

    @Autowired
    private ServiceReasonstopMapper reasonstopMapper;

    @Autowired
    private ServiceActionMapper actionMapper;

    @Autowired
    private ServiceLogMapper logMapper;

    @Autowired
    private ServiceReasonMapper reasonMapper;



    @Transactional //需要
    public Page<PCUserListRet> getUserList(String labelStatus, Integer page, Integer size)
    {
        List<PCUserListRet> retUsersList = new ArrayList<PCUserListRet>();
        try {
            List<ServiceUsers> users = usersMapper.selectServiceUsersListNew();
            for (ServiceUsers user : users) {
                PCUserListRet retNode = new PCUserListRet();
                retNode.init(user);
                List<ServiceOrders> orders = ordersMapper.selectServiceOrdersByUserId(user.getUsersId());
                retNode.setOrderCount(Long.valueOf(orders.size()));
                retUsersList.add(retNode);
            }

            // 分页逻辑
            Pageable pageable = PageRequest.of(page, size);
            int start = (int) pageable.getOffset();
            int end = Math.min((start + pageable.getPageSize()), retUsersList.size());
            List<PCUserListRet> pagedItemsList = retUsersList.subList(start, end);

            return new PageImpl<>(pagedItemsList, pageable, retUsersList.size());

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public PCUserDetailRet getUserDetail(Long userId) {
        try {
            ServiceUsers user = usersMapper.selectServiceUsersByUsersId(userId);

            PCUserDetailRet retNode = new PCUserDetailRet();
            retNode.init(user);
            if(user.getUsersLogid()!=null){
                List<ServiceLog> logList = logMapper.selectServiceLogByUserId(userId);
                List<PCUserLog> retLogList = new ArrayList<PCUserLog>();
                for (ServiceLog log : logList) {
                    PCUserLog logNode = new PCUserLog();
                    logNode.init(log);
                    retLogList.add(logNode);
                }
                retNode.setLog(retLogList);
            }

            return retNode;

        }catch (Exception e){
            return null;
        }
    }

    @Transactional
    public List<Map<String, Object>> getLockReason() {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            ServiceReason reasonSearch = new ServiceReason();
            reasonSearch.setReasonUseFlag("0");
            List<ServiceReason> reasons = reasonMapper.selectServiceReasonList(reasonSearch);

            for(ServiceReason reason : reasons){
                Map<String, Object> reasonMap = new HashMap<>();
                reasonMap.put("id", reason.getReasonId());
                reasonMap.put("reason", reason.getReasonName());
                result.add(reasonMap);
            }
            return result;

        }catch (Exception e){
            return null;
        }

    }

    @Transactional
    public Integer userLock(Long userId, Long reasonId, String remark) {
        ServiceUsers users = usersMapper.selectServiceUsersByUsersId(userId);
        if (users != null){
            if ("0".equals(users.getUsersUseFlag())){
                ServiceReason reason = reasonMapper.selectServiceReasonByReasonId(reasonId);
                ServiceLog newLog = new ServiceLog();
                newLog.setLogUserid(userId);
                newLog.setLogDate(new Date());
                newLog.setLogTime(new Date());
                newLog.setLogType("锁定");
                newLog.setLogReasonexplanation(reason.getReasonName() + "（" + remark + "）" );
                newLog.setLogUserBy(getUsername());

                logMapper.insertServiceLog(newLog);

                users.setUsersUseFlag("1");
                users.setUsersReasonid(reasonId);
                users.setUsersExplanation(reason.getReasonName() + "（" + remark + "）" );
                users.setUsersLogid(newLog.getLogId());
                users.setUsersUpdateBy(getUsername());
                users.setUsersUpdateTime(new Date());

                usersMapper.updateServiceUsers(users);

                return 0;
            }
        }
        return 1;
    }

    @Transactional
    public Integer userUnlock(Long userId) {
        ServiceUsers users = usersMapper.selectServiceUsersByUsersId(userId);
        if (users != null){
            if ("1".equals(users.getUsersUseFlag())){
                ServiceLog newLog = new ServiceLog();
                newLog.setLogUserid(userId);
                newLog.setLogDate(new Date());
                newLog.setLogTime(new Date());
                newLog.setLogType("解锁");
                newLog.setLogReasonexplanation("手动解锁");
                newLog.setLogUserBy(getUsername());

                logMapper.insertServiceLog(newLog);

                users.setUsersUseFlag("0");
                users.setUsersUpdateBy(getUsername());
                users.setUsersUpdateTime(new Date());

                usersMapper.updateServiceUsers(users);
                return 0;
            }
        }
        return 1;
    }
}
